package com.equipment.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.equipment.management.dao.LogDao;
import com.equipment.management.dao.MainframeDao;
import com.equipment.management.dao.MainframeScanResultDao;
import com.equipment.management.dao.MessageDao;
import com.equipment.management.entity.*;
import com.equipment.management.service.MainframeService;
import com.equipment.management.util.Base64Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2017/8/16.
 */
@Slf4j
@Service
public class MainframeServiceImpl extends Base64Util implements MainframeService {
    @Autowired
    private MainframeDao mainframeDao;//这里会报错，但是并不会影响
    @Resource
    private LogDao logDao;
    @Resource
    private MessageDao messageDao;

    @Resource
    private MainframeScanResultDao mainframeScanResultDao;

    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单，只需要在service层传入参数，然后将参数传递给一个插件的一个静态方法即可；
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public PageInfo<Mainframe> findAllMainframe(int pageNum, int pageSize, String room_num) {
        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<Mainframe> mainframeDomains = mainframeDao.selectMainframes(room_num);
        PageInfo result = new PageInfo(mainframeDomains);
        return result;
    }


    @Override
    public int addMainframe(Mainframe mainframe) throws Exception {
        mainframe.setId(UUID.randomUUID().toString().replace("-", ""));
        mainframe.setCreate_time(new Date());

//        //获得系统端口列表
//        getSystemPort();
//        //开启端口
//        final SerialPort serialPort = openSerialPort("COM1", 115200);
//        if (serialPort != null) {
//            String s = "set ssid:"+mainframe.getWifi_account()+" pwd:"+mainframe.getWifi_password()+ " ip:"+mainframe.getIp()+" +"+mainframe.getId();
//            log.info("串口参数：{}",s);
//
//            byte[] bytes = s.getBytes();
//            SerialComm.sendData(serialPort, bytes);
//        }
        log.info("主机参数：{}",mainframe);
        return mainframeDao.addMainframe(mainframe);
    }

    @Override
    public int deleteMainframe(List<String> id) {
        int i = mainframeDao.deleteMainframe(id);
        return i;
    }

    @Override
    public Mainframe getMainframeByCode(String code) {
        Mainframe us = mainframeDao.getMainframeByCode(code);
        return us;
    }

    @Override
    public List<Mainframe> getAllmainframe() {
        QueryWrapper<Mainframe> queryWrapper = new QueryWrapper<>();
        List<Mainframe> us = mainframeDao.selectList(queryWrapper);
        return us;
    }

    @Override
    public List<String> getAllPort(String port) {

        List<String> us = mainframeDao.getAllPort(port);
        return us;
    }

    @Override
    public List<String> getAllType(String type) {
        List<String> us = mainframeDao.getAllType(type);
        return us;    }

    @Override
    public void updateInitMainframe(String topic, List<String> list, String operate, String random) {
        mainframeDao.updateInitMainframe(topic);

        mainframeDao.deleteMainframeResult(topic,random);
        for(String result:list ){
            MainframeResult m=new MainframeResult();
            m.setCode(topic);
            m.setResult(result);
            m.setCreate_time(new Date());
            m.setRandom(random);
            mainframeDao.insertMainframeResult(m);
        }


        //*========数据库日志=========*//
        Log log=new Log();
        log.setRemark(topic+"初始化");
        log.setOperate(operate);
        log.setCreate_time(new Date());
        log.setTopic(topic);
        //保存数据库
        logDao.insert(log);

    }

    @Override
    public void updateMainframeResult(String topic, String payload, String operate, List<String> list, String random) {
    try {
        Mainframe mainframe = mainframeDao.getMainframeByCode(topic);

        String code= list.get(0).substring(0,8);

        MainframeScanResult mainframeScanResult=new MainframeScanResult();
        //黑名单
        int whitecount =mainframeDao.getWhiteframe(code);

        String second=list.get(0).substring(1,2);


        int blackcount =mainframeDao.getBlackframe(code);

        if(blackcount>0){
            log.info("黑名单存在");
            mainframeScanResult.setReturn_message("bj");//报警

        }else if (StringUtils.isEmpty(payload)) {
            mainframeScanResult.setReturn_message("gz");//故障

        } else if (!StringUtils.isEmpty(payload)) {
            List<String> resultlist = mainframeDao.getMainframeResult(topic,list.get(0));

            if(resultlist.size()>0){
                mainframeScanResult.setReturn_message("zc");//正常

            }else{
             if ("2,6,a,e,A,E".contains(second)){
                mainframeScanResult.setReturn_message("zc");//正常
            }else if(whitecount>0){
                 log.info("白名单存在");
                mainframeScanResult.setReturn_message("zc");//正常
            }else{
                mainframeScanResult.setReturn_message("bj");//报警
            }
            }
        }
        mainframeScanResult.setCreate_time(new Date());
        mainframeScanResult.setCode(topic);
        mainframeScanResult.setRandom(random);
        mainframeScanResult.setResult(list.get(0));
        mainframeScanResultDao.insert(mainframeScanResult);
        //mainframeDao.updateMainframeResult(topic, mainframe.getResult(), mainframe.getReturn_message());



    }catch (Exception e){
        log.info("异常：{}",e);
    }



    }

    @Override
    public void closeMainframeResult(String topic, String operate) {
        mainframeDao.closeMainframeResult(topic,"close");

        //*========数据库日志=========*//
        Log log=new Log();
        log.setTopic(topic);
        log.setOperate(operate);
        log.setRemark(topic+"关闭");
        log.setCreate_time(new Date());
        //保存数据库
        logDao.insert(log);
    }

    @Override
    public Map getCountByType() {
        return mainframeDao.getCountByType();
    }

    @Override
    public Map getCountByLevel(String floor_level) {
        return mainframeDao.getCountByLevel(floor_level);
    }

    @Override
    public List<Map> getAllFloorRoom(String floor_level, String room_num) {
        return mainframeDao.getAllFloorRoom(floor_level,room_num);
    }

    @Override
    public int getScanMainFrame(List<String> list) {
        return mainframeDao.getScanMainFrame(list);
    }

    @Override
    public PageInfo<Map> getLog(int pageNum, int pageSize, String code, String operate) {

        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<Map> userDomains = mainframeDao.getLog(code,operate);
        PageInfo result = new PageInfo(userDomains);
        return result;
    }

    @Override
    public PageInfo<Map> getMessage(int pageNum,int pageSize,String operate) {

        //将参数传给这个方法就可以实现物理分页了，非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List<Map> userDomains = messageDao.getMessage(operate);
        PageInfo result = new PageInfo(userDomains);
        return result;
    }

    @Override
    public void updateMessage(String id) {
        messageDao.updateMessage(id);
    }


}
